package com.github.data_manage.dao

import com.github.data_manage.domain.po.FundReturnData
import org.springframework.data.jpa.repository.Modifying
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param
import org.springframework.transaction.annotation.Transactional
import java.time.LocalDate
import java.time.LocalDateTime

/**
 *@author CHN
 *@since 2024-08-10 14:48
 */
interface FundReturnDataDao : BaseDao<FundReturnData> {

    @Query("select f from FundReturnData f where f.fundId = :fundId and f.time <= :lastMonth order by f.time desc limit 1")
    fun findLastNavDataByFundId(
        @Param("fundId") fundId: Int,
        @Param("lastMonth") lastMonthEndTime: LocalDateTime
    ): FundReturnData?

    @Query("select f from FundReturnData f where f.fundId = :fundId and f.time = :lastMonth order by f.time desc limit 1")
    fun findByFundIdAndTime(fundId: Int,  @Param("lastMonth") lastMonthEndTime: LocalDate): FundReturnData?

    fun findAllByFundId(fundId: Int): List<FundReturnData>

    fun findAllByFundIdAndTimeBetween(fundId: Int, startTime: LocalDate, endTime: LocalDate): List<FundReturnData>

    @Modifying
    @Transactional
    fun deleteAllByFundId(fundId: Int)

    fun findAllByFundIdIn(fundIds: List<Int>): List<FundReturnData>

    @Query("""
        SELECT 0 as id, fund_id, fund_name, MAX(abs(value)) AS value,now() as time
        FROM t_fund_return_data
        GROUP BY fund_id, fund_name
        order by value
    """, nativeQuery = true)
    fun findMaxReturnData(): List<FundReturnData>

    @Modifying
    @Query("update FundReturnData f set f.fundName = :fundName where f.fundId = :fundId")
    fun updateFundNameByFundId(@Param("fundId") fundId: Int,
                               @Param("fundName") name: String)
}
